import win32com.client as win32

def cm_to_inch(cm):
    return cm / 0.393701
excelFileName = "陈店镇 - 最新 - 修改好"  # 新生成的Excel名称

# 打开Excel文件
file_path = rf'D:\Windows\{excelFileName}.xlsx'
excel = win32.Dispatch("Excel.Application")
excel.Visible = False  # 不显示Excel窗口
workbook = excel.Workbooks.Open(file_path)

# 设置页面布局
for sheet in workbook.Sheets:
    page_setup = sheet.PageSetup

    # 设置页边距，转换为英寸
    # page_setup.LeftMargin = cm_to_inch(1.2)  # 左边距 1.2 厘米
    # page_setup.RightMargin = cm_to_inch(0.8)  # 右边距 0.8 厘米
    # page_setup.TopMargin = cm_to_inch(1.9)  # 上边距 1.9 厘米
    # page_setup.BottomMargin = cm_to_inch(1.9)  # 下边距 1.9 厘米
    # page_setup.HeaderMargin = cm_to_inch(1.27)  # 页眉边距 1.27 厘米
    # page_setup.FooterMargin = cm_to_inch(1.27)  # 页脚边距 1.27 厘米

    page_setup.LeftMargin = cm_to_inch(10)  # 左边距 1.2 厘米
    page_setup.RightMargin = cm_to_inch(10)  # 右边距 0.8 厘米
    page_setup.TopMargin = cm_to_inch(8)  # 上边距 1.9 厘米
    page_setup.BottomMargin = cm_to_inch(10)  # 下边距 1.9 厘米
    # page_setup.HeaderMargin = cm_to_inch(35)  # 页眉边距 1.27 厘米
    page_setup.FooterMargin = cm_to_inch(8)  # 页脚边距 1.27 厘米
    # 设置页脚内容
    page_setup.CenterFooter = "第 &P 页，共 &N 页"  # 设置居中页脚内容

    # 设置纸张方向为横向
    page_setup.Orientation = 2  # xlLandscape

    # 设置纸张大小为 A4
    page_setup.PaperSize = 9  # xlPaperA4

    # 设置是否显示网格线
    page_setup.PrintGridlines = False

    # 设置缩放比例为 100%
    page_setup.Zoom = 100

    # 设置是否水平和垂直居中
    page_setup.CenterHorizontally = True
    # page_setup.CenterVertically = True

# 保存并关闭工作簿
workbook.SaveAs(rf'D:\Windows\{excelFileName}+2222121.xlsx')
workbook.Close()
excel.Quit()

print("页面设置已成功应用到所有工作表。")
